import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TimeConfigClass } from '../../common/common-config';
import { StorageService } from "../../common/storage.service";
import { CatalogService } from './catalog.service';

@Component({
  selector: 'app-catalog',
  templateUrl: './catalogList.component.html',
  styleUrls: ['./catalogList.component.css'],
  providers: [CatalogService],
  styles: [':host /deep/ .ui-datatable{margin-top:29px} :host /deep/ .staff .org .relative{display:inline-block} :host /deep/ .staff .org .relative .ui-tree-container{display:block} .m-l-26{margin-left:26px}']
})
export class CatalogListComponent implements OnInit {
  //列表
  timeConfig: any = new TimeConfigClass(); // 时间空间初始化
  colsSelected: any;
  cols: any = [];
  selectedItem: any = []; //选中记录
  pageSize: number; // 每页条数
  pageNo: number; // 当前页
  listData: any = []; // 数据
  totalRecords: number; // 数据条数
  searchObj: any = {}; // 搜索条件
  searcSortObj: any = {}; // 排序信息
  submited: boolean ;

  siteArr: any = []; //网站
  tree: any[] = []; //目录
  selectedFiles: any = [];
  levelArr: any = [];
  
  constructor(private storage: StorageService, private route: ActivatedRoute, private router: Router, private server: CatalogService) {

    this.cols = [
      { field: 'name', header: '名称', frozen: false, sortable: true, tem: true, width: '8%' },
      { field: 'alias', header: '别名', sortable: true, width: '10%' },
      { field: 'templateName', header: '模板', sortable: true, width: '8%' },
      { field: 'keywords', header: '关键词', sortable: true, width: '18%' },
      { field: 'description', header: '描述', sortable: true, width: '8%' },
      { field: 'level', header: '级别', sortable: true, width: '8%' },
      { field: 'sortNum', header: '序号', sortable: true, width: '8%' },
      { field: 'dateCreate', header: '创建时间', sortable: true, width: '8%' }
    ];

    this.colsSelected = this.cols;

  }

  ngOnInit() {

      this.findSite()
      this.levelArr = [{code:'',name:"请选择"},{code:1,name:"一级"},{code:2,name:"二级"},{code:3,name:"三级"}]
  }

  //新建
  add() {
    //debugger
    this.router.navigate(['../catalogAdd', '0'], { relativeTo: this.route }); // 相对于当前路由跳转
    // this.router.navigate(['/saas/sys/system/staffManagement/add']); // 相对于绝对路径跳转
  }

  /**
   * 编辑
   */
  edit(code) {
    if(code==undefined){
      this.storage.messageService.emit({ severity: 'error', detail:'失败' })
      return false;
    };
    this.router.navigate(['../catalogAdd', code], { relativeTo: this.route }); // 相对于当前路由跳转
  }


  /**
   * 获取数据
   */
  getData(params) {
    if(!params.siteCode){
      return false;
    }
    //let params = this.searchObj;
    this.storage.loading();
    this.server.list(params, this.pageSize, this.pageNo).then(
      data => {
        this.storage.loadout();
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
          this.selectedItem = []; //选中记录置空
        } else {
          this.listData = [];
          this.totalRecords = 0;
        }
      }
    );
  }
  /**
   *删除数据
   */
  delete() {
    let list = this.selectedItem;
    if (list.length != 1) {
      this.storage.messageService.emit({severity:'warn', detail:'请选择一个栏目'})
      return false;
    };
    let id = list[0].id; 
    let params = {id:id};
    this.server.delete(params).then(data => {
      if (data.result) {
        this.storage.messageService.emit({severity:'success', detail:data.msg})
        this.search();
        console.log(data.msg)
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:data.msg})
        console.log(data.msg)
      }
    });
  }
  /**
   * 改变模糊搜索框数据值
   */
  searchTextChange(event) {
    if (event == undefined)
      return false
    if (event.constructor == String && event != '') {
      this.searchObj['searchValue'] = event;
    } else {
      this.searchObj['searchValue'] = undefined;
    };
  }
  /**
   * 搜索方法
   * @param event
   */
  search(event?) {
    //筛选查询
    this.searchTextChange(event);
    // this.pageNo = 1;
    const params = Object.assign(this.searchObj);
    params.catalogCode = this.selectedFiles ? this.selectedFiles.code  : '';
    this.getData(params);
  }
  /**
   * 分页查询
   * @param event
   */
  loadCarsLazy(event) {
    this.pageSize = + event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    this.searcSortObj['sortF'] = event.sortField;
    this.searcSortObj['sortO'] = event.sortOrder == 1 ? 'asc' : 'desc';
    const params = Object.assign(this.searchObj, this.searcSortObj);
    this.getData(params);
  }

  /**
   * 获取网站
   */
  findSite() {
    let params = {};
    this.server.findSite(params).then(data => {
      if (data.result) {
        this.siteArr = data.data
        this.searchObj.siteCode = this.siteArr[0].code;
        this.findTree();
        this.search();
        console.log('获取网站成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'获取网站失败' })
        console.log('获取网站失败')
      }
    });
  }

  /**
   * 获取目录
   */
  findTree() {
    const params = Object.assign(this.searchObj);
    this.server.findTree(params).then(data => {
      if (data.result) {
        let dat = data.data
        dat.unshift({ code: params.siteCode , label: '首页','children':[] });
        this.expandAll(dat);
        this.tree = dat;
        console.log('获取目录成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'获取目录失败' })
        console.log('获取目录失败')
      }
    });
  }

  /**
   * 
   * @param data 树
   */
  expandAll(data){
    data.forEach( node => {
      this.expandRecursive(node, true);
    } );
  }

  private expandRecursive(node, isExpand:boolean){
    node.expanded = isExpand;
    if(node.children){
      node.children.forEach( childNode => {
        this.expandRecursive(childNode, isExpand);
      } );
    }
  }

}
